<?php
namespace Admin\Controller;

use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminListBuilder;
//use Admin\Builder\AdminTreeListBuilder;  


class ChengjiController extends AdminController
{
    protected $studentModel;
    protected $classModel;

    function _initialize()
    {
        parent::_initialize();
        header("Content-Type:text/html;charset=utf-8"); 
        $this->studentModel = D('Chengji/ChengjiStudent'); 
        //$this->classModel=D('Chengji/ChengjiClass');
        $this->studentScoreModel=D('Chengji/ChengjiStudentScore');
        $this->kaoshiModel=D('Chengji/ChengjiKaoshi');
        $this->yearModel=D('Year');
        $this->termModel=D('YearTerm');
        $this->curTerm=$this->termModel->where('cur=1')->getfield('term');
        $this->curYear=I('year',$this->yearModel->where('cur=1')->getfield('year'));
        $this->studentClassModel=D('Student/StudentClass');//学生班级表
        // dump($this->studentClassModel);
        $this->gradeModel=D('Student/StudentGrade');
        $this->classscoreModel=D('Chengji/ChengjiClassScore');
        $this->stuentModel=D('ChengjiStudent');
        //dump($this->kaoshiModel);
        
    }
    /**学生考试登记*/
    public function kaoshi(){
    	$map=array('status'=>1);
        $builder = new AdminListBuilder();

        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $list=$this->kaoshiModel->where($map)->order('id desc')->select();
        $builder->title('考试管理')
        ->buttonNew(U('Chengji/editKaoshi'))        
        ->buttonDeleteTrue(U('Wckc/deleteClass'),'')
        ->buttonDelete(U('Wckc/deleteClass'),'删除')
        //->buttonSort(U('Wckc/sortClass'),'排序',array('class' =>'btn btn-success'))
        
        ->keyId()->keyText('year','学年')
        ->keyText('term','学期')
        ->keyText('name','考试名称')
        ->keyText('name_s','考试简称')
        ->keyText('subject','考试科目')
        ->keyText('uid','用户id')
        //->keyText('sort','排序')        
        
        ->keyDoActionEdit('editkaoshi?id=###','编辑')
        ->keyDoAction('deleteClass?ids=###',"删除")
        ->data($list) 
        ->display();
    }
    /**导入年级学生成绩*/
    public function importGradescore(){

    	 $list=$this->kaoshiModel->where($map)->order('id desc')->select();
    	 $this->assign('kaoshi_list',$list);
    	 // dump($list);
    	 $this->assign('meta_title','按年级导入学生成绩');
         $this->display('Chengji@Admin/import_gradescore');  
    }
    public function doGradescoreUpload(){
    	$kid=I('kid',intval);
    	if(!$kid){
    		$this->error('请先选择考试项目');
    	}
    	$term=I('term',$this->curTerm);
        $config = array(
                    'maxSize'    =>   30*1024*1024, // 设置附件上传大小
                    'rootPath'   =>  './Uploads/',
                    'savePath'   =>   'Tmp/',// 设置附件上传目录
                    'saveName'   =>   array('uniqid'),//iconv('utf-8', 'gbk', $save),
                    'exts'       =>    array('xls', 'xlsx'),// 设置附件上传类
                    'autoSub'    =>    true,
                    'subName'    =>    array('date','Y-m'),
                    );
                $upload = new \Think\Upload($config);// 实例化上传类

                // 上传文件
                $info   =   $upload->uploadOne($_FILES['excelData']);      
                $filename = './Uploads/'.$info['savepath'].$info['savename'];
                $exts = $info['ext'];
                // print_r($info);exit;
                if(!$info) {// 上传错误提示错误信息
                      $this->error($upload->getError());
                  }else{
                  // 上传成功
                  $data=readexcel2arryByTitle($filename, $exts,3);//[文件URL,扩展名,指示标题行数]
                  $this->saveStudentScore($data,$kid,$term);
                }
               
    }
    private function saveStudentScore($data,$kid,$term){
    	//dump($kid);
    	//dump($term);die;
    	$title=$data['title'];//标题数组
    	
    	//$studentinfo=array_slice($data['title'],0,4);//标题中的学生信息
    	//dump($studentinfo);
    	$subjectlist=array_slice($data['title'],4);//从标题分割出科目 [班级,学号,姓名,性别]
    	$column=array(
    		'bj_name'=>array_shift(array_keys($title,'班级')),
    		'st_code'=>array_shift(array_keys($title,'学号')),
    		'st_name'=>array_shift(array_keys($title,'姓名')),
    		'sex'=>array_shift(array_keys($title,'性别')),
    		);
    	
    	$list=$data['data'];//成绩二维数组
    	$scoreModel=$this->studentScoreModel;
    	$studentclassModel=$this->studentClassModel;//学生管理模块中的班级表
    	$add_count = 0;//增加统计
        $update_count = 0;//更新统计
        $unmodif_count=0;//未被修改数据 统计
    	foreach($list as $row){

    		$bj_map=array(
    			'bj_name'=>$row[$column['bj_name']],
    			'year'=>$this->curYear
    			);    		
    		$thisClass = $studentclassModel->where($bj_map)->field('grade,bj_code,bj_name')->find(); 
    		$st_info_map=array(
    			'bj_name'=>$row[$column['bj_name']],
    			'st_name'=>$row[$column['st_name']],
    			'bj_code'=>$thisClass['bj_code'],
    			'term'=>$term
    			);
    		//dump($st_info_map);
    		$find_st=$this->stuentModel->where($st_info_map)->find();
    		if(!$find_st){
    			$st_info_data=array_merge($st_info_map,
    				array(
    					'st_code'=>$row[$column['st_code']],
    					'sex'=>$row[$column['sex']]
    				));

    			    			
    			// dump($st_info_data);$st_info_data=$this->stuentModel->create($st_info_data);dump($st_info_data);die;
    			$this->stuentModel->add($st_info_data);

    		}


    		foreach($subjectlist as $key=>$subject){
    			
    			$map=array(
    			'kid'=>$kid,
    			'grade'=>$thisClass['grade'],
    			'bj_code'=>$thisClass['bj_code'],
    			'bj_name'=>$thisClass['bj_name'],
    			'st_name'=>$row[$column['st_name']],
    			'subject'=>$subject,    			
    			);

    			
    		    $rs_find=$scoreModel->where($map)->find();

    		    if(!$rs_find){
    		    	$savedata=array_merge($map,
		    		    	          array(
				    		    		'sex'=>$row[$column['sex']],
				    		    		'st_code'=>$row[$column['st_code']],
				    		    		'score'=>$row[$key],
				    		    		'term'=>$term,
				    		    		'create_time'=>NOW_TIME,
				    		    		//'update_time'=>NOW_TIME
				    		    		)
    		    		    );//与查询条件合并
    		    	
    		    	$savedata=$scoreModel->create($savedata);
    		    	//dump($savedata);  		    	
    		    	$resid=$scoreModel->add();
    		    	if($resid) $add_count++;    		    	

    		    }else{
    		    	
    		    	if($rs_find['score']!=$row[$key]){
    		    		$up_data=array_merge($map,
    		    			array(
    		    			'id'=>$rs_find['id'],
    		    			'kid'=>$rs_find['kid'],
    		    			'score'=>$row[$key],
    		    			'update_time'=>NOW_TIME
    		    			));
    		    		$up_data=$scoreModel->create($up_data);
    		    		
    		    		$update_id=$scoreModel->where($map)->save($up_data);
    		    		if($update_id) $update_count++;
    		    		
    		    	}else{
    		    		$unmodif_count++; 
    		    	}

    		    	
    		    }
    		  
    		}
    		unset($up_data);
    		unset($savedata);

    	}
    	//die;
         $masseg_str='本次共增加'.$add_count.'条记录，更新'.$update_count.'条记录， 未修改记录'.$unmodif_count.'条!';//提示信息
         $this->success($masseg_str,'Admin/Chengji/importGradescore',10);
    	
    }

    public function index(){       
        
        /**设置自动转向 **/
        $this->redirect('importGradescore');
    }


    /*班级信息编辑*/
    public function editkaoshi()
    {
        $id=I('id');
        $title_str = $id ? '编辑' : '新增';
        $kaoshiModel=$this->kaoshiModel;

    	if(IS_POST){
    		$data=I('post.');
    		$id=$data['id'];
	        if ($data['name']==''){
                $this->error('考试名称不能为空');
            }
            if ($data['name_s']==''){
                $this->error('考试简称不能为空');
            }
    		$data=$kaoshiModel->create($data);
    		// dump($data);die;
    		if($id){
	    		if ($kaoshiModel->save($data)){
	    		    $this->success('编辑成功。');
	    		} else {
	                $this->error('编辑失败。');
	            }
    		}else{
    			if ($kaoshiModel->add($data)){
	    		    $this->success('新增成功。');
	    		} else {
	                $this->error('新增失败。');
	            }
    		}

    	}else{
    		$builder = new AdminConfigBuilder();
    		if($id){
    		   $data=$this->kaoshiModel->find($id); 
    		} else{
    			$data=array('term' =>$this->curTerm, 'year' => $this->curYear, 'status' => 1);
    		}   		
	    		 
    		  $builder->title($title_str.'考试信息')->keyId('id','考试ID')
    		    ->keyText('year','学年')
		        ->keyText('term','学期')
		        ->keyText('name','考试名称')
		        ->keyText('name_s','考试简称')
		        ->keyText('subject','考试科目')		        
                ->keyStatus()
                ->keyCreateTime()->keyUpdateTime()
                ->data($data)
                ->buttonSubmit()->buttonBack()->display();

    	}
    	//dump($id);

    }

     public function classManage(){
        $map=array('status'=>1);
        $builder = new AdminListBuilder();

        // 记录当前列表页的cookie
         Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $list=$this->classModel->where($map)->order('sort asc, grade asc')->select();
        $builder->title('班级管理')
	        ->buttonNew(U('Wckc/editClass'))        
	        ->buttonDeleteTrue(U('Wckc/deleteClass'),'')
	        ->buttonDelete(U('Wckc/deleteClass'),'删除')
	        ->buttonSort(U('Wckc/sortClass'),'排序',array('class' =>'btn btn-success'))
	        
	        ->keyId()->keyText('grade','年级')
	        ->keyText('bj_code','班级编号')
	        ->keyText('bj_name','班级名称')
	        ->keyText('bj_name2','班级简称')
	        ->keyText('headteacher','班主任')
	        ->keyText('sort',L('排序'))
        
        
        ->keyDoActionEdit('editClass?id=###','编辑')
        ->keyDoAction('deleteClass?ids=###',"删除")
        ->data($list) 
        ->display();
     }
     /**
     * 班级排序
     * @author shuiyueju <singliang@163.com>
     */
    public function sortClass(){
        $model=$this->classModel;
        if(IS_GET){
            $ids = I('get.ids');
           
            //获取排序的数据
            $map = array('status'=>array('gt',-1));
            // $map['hide']=0;
            if(!empty($ids))$map['id'] = array('in',$ids);

            $list = $model->where($map)->field('id,bj_name as title')->order('sort asc,id asc')->select();

            $this->assign('list', $list);
            $this->meta_title = '班级排序';
            $this->subnav=U('Chengji/classSort');//菜单高亮
            $this->display('Chengji@Admin/sort');
        }elseif (IS_POST){
            $ids = I('post.ids');
            $ids = explode(',', $ids);

            foreach ($ids as $key=>$value){
                $res =$model->where(array('id'=>$value))->setField('sort', $key+1);
            }
            if($res !== false){
                $this->success('排序成功！');
            }else{
                $this->error('排序失败！');
            }
        }else{
            $this->error('非法请求');
        }
    } 


        //导入学生名单 上传excel方法
        public function importClass(){
            
            if(IS_POST){
                $config = array(
                    'maxSize'    =>   30*1024*1024, // 设置附件上传大小
                    'rootPath'   => './Uploads/',
                    'savePath'   =>     'Tmp/',// 设置附件上传目录
                    'saveName'   =>   array('uniqid'),//iconv('utf-8', 'gbk', $save),
                    'exts'       =>    array('xls', 'xlsx'),// 设置附件上传类
                    'autoSub'    =>    true,
                    'subName'    =>    array('date','Y-m'),
                    );
                $upload = new \Think\Upload($config);// 实例化上传类

                // 上传文件
                $info   =   $upload->uploadOne($_FILES['excelData']);      
                $filename = './Uploads/'.$info['savepath'].$info['savename'];
                $exts = $info['ext'];
                
                if(!$info) {// 上传错误提示错误信息
                      $this->error($upload->getError());
                  }else{
                  // 上传成功
                   $this->class_import($filename, $exts);
                }

            }else{
                $map['wckcstatus']=1;
                $this->list=$this->classModel->where($map)->order('sort asc')->select();
                $this->assign('meta_title','导入班级信息');
                $this->display('Chengji@Admin/importClass2');
            }

        }



    public function score(){
        $this->meta_title = '期末成绩管理';
        //$map=array('grade'=>'2');
        $classlist=$this->classModel->field('bj_name as id, bj_name as title')->select();
        array_unshift($classlist,array('id'=>'全部','title'=>'全部'));
          for($i=0;$i<count($classlist);$i++)
          {
              $classlist[$i]['id']=$classlist[$i]['value']= $classlist[$i]['title'];
          }
        // dump($classlist);
         $class=I('class','全部');
        if($class=='全部') {
            unset($map['class']);
            $map['status']=1;
        }else{
           $map=array(
            'class'=>$class,
            'status'=>1
            ); 
        }
        // dump($map);die;
        $model=D('WckcStudent');
        $r=I('r',20);
        $list = $model->where($map)->order('code asc, update_time desc')->page($page, $r)->select();
        $totalCount = $model->where($map)->count();
        
        $builder = new AdminListBuilder();
        $builder->title('期末成绩管理')
            ->setStatusUrl(U('Forum/setPostStatus'))->buttonEnable()->buttonDisable()
            ->buttonDelete()
            ->setStatusUrl(U('wckc/deleteScore'))
            //->key()
            //->buttonModalPopup(U('Forum/changePlate', array('forum_id'=>$map['forum_id'])), array(), L('_MIGRATING_NOTE_'),array('data-title'=>L('_MIGRATING_NOTE_TO_ANOTHER_PLATE_'),'target-form'=>'ids'))
            //->selectPlateForm('spf',get,U('Admin/Forum/post'))
            ->select($title = '筛选：', $name = 'class','select', '', '', '',$classlist)
            ->keyId('code','学号')->keyText('class','班级')->keyText('name','姓名')->keyText('sex','性别')
            ->keytext('score', '成绩')->keyBool('outstand', '优秀学员', 'text')
             ->keyUpdateTime()->keyStatus()->keyDoActionEdit('editPost?id=###')
            //->setSearchPostUrl(U('Admin/Wckc/searchstudent'))->search('姓名', 'name')->search('班级', 'class')
            ->data($list)
            ->pagination($totalCount, $r)
        ->display();
       
        // $this->display('Student@Admin/score'); 
    }
    /**学生管理  */
        public function student(){
        $this->meta_title = '学生管理';
        //$map=array('grade'=>'2');
        $classlist=$this->classModel->field('bj_name as id, bj_name as title')->select();
        array_unshift($classlist,array('id'=>'全部','title'=>'全部'));
          for($i=0;$i<count($classlist);$i++)
          {
              $classlist[$i]['id']=$classlist[$i]['value']= $classlist[$i]['title'];
          }
        
         $class=I('class','全部');
        if($class=='全部') {
            unset($map['class']);
            $map['status']=1;
        }else{
           $map=array(
            'class'=>$class,
            'status'=>1
            ); 
        }
        $name=I('name','');
        // dump($name);
        if(!empty($name)){
            $map['name']=array('like','%'.$name.'%');
        }else{
            unset($map['name']);
        }
        // dump($map);die;
        $model=D('WckcStudent');
        $r=I('r',20);
        $list = $model->where($map)//->field('id, class, code, name, sex, update_time, status')
                ->order('code asc, update_time desc')->page($page, $r)->select();
        // dump($list);die;
        $totalCount = $model->where($map)->count();
        
        $builder = new AdminListBuilder();
        $builder->title('学生管理')
            ->setStatusUrl(U('wckc/setPostStatus'))->buttonEnable()->buttonDisable()
            ->buttonDelete()->setStatusUrl(U('wckc/deleteStudent'))
            ->setSearchPostUrl(U('Admin/Wckc/student'))->search('姓名', 'name')->search('班级', 'class')

            ->select($title = '筛选：', $name = 'class','select', '', '', '',$classlist)
            // ->keyId()
            ->keyText('class','班级')->keyText('code','学号')->keyText('name','姓名')->keyText('sex','性别')
            ->keyText('cid','课程ID')            
             ->keyUpdateTime()->keyStatus()->keyDoActionEdit('editStudent?id=###')
            
            ->data($list)
            ->pagination($totalCount, $r)
        ->display();
       
        // $this->display('Student@Admin/score'); 
    }
 
    public function editStudent(){
        $id=I('id');
            if(IS_POST){

            $data=$this->studentModel->create();
            // dump($aclass);exit;
            if ($this->studentModel->save($data)){
                $this->success('编辑成功。');
            } else {
                $this->error('编辑失败。');
            }
        }

        if(!$id){
            $this->error('学生ID不存在');
        }else{
            $data=$this->studentModel->find($id);
             $builder = new AdminConfigBuilder();
              $builder->title('编辑学生信息')->keyId('id','学生ID')
              ->keyText('class', '班级名称')->keyText('name', '姓名')
              ->keyText('sex', '性别')

                //->keyStatus()
                ->keyCreateTime()->keyUpdateTime()
                ->data($data)
                ->buttonSubmit(U('Wckc/editStudent'))->buttonBack()->display();
        }


    }
        /**
         * 清除课程成绩
        */
    public function deleteScore(){
        
        $this->Model=D('ChengjiStudent');
        $where=array("status"=>"1");
        $data=array(
            'score'=>'',
            'outstand'=>'0'
            );      
 
        $list=$this->Model        
        ->where($where)->setField($data);
        if($list){
             $this->error('数据清除失败！');
        }else{
            $this->success('数据清除成功！',U('index')); 
        }
              
    }
        /*班级列表*/
      public function deleteStudent()
      {
        $id=I('id');
        $map=array('sid'=>$id);
        $class=$this->studentModel->where($map)->getField('class');
        //dump($class);die;

        $res=$this->studentModel->delete($id);
        if($res){
            $this->success( '删除学生成功', U('Admin/Wckc/classlist', array('class'=>$class) ), 3);
        }else{
            $this->error('删除学生失败');
        }


      }

    /*班级列表*/
      public function classlist()
    {
        $map = array('wckcstatus' => 1);
        //排序设置
        $order=array( 'sort'=>'asc');
        $classModel = $this->classModel;
        $studentModel=$this->studentModel;
        $classlist=$classModel->field('id,bj_name')->where($map)->order($order)->select();
        $aClass=I('class','所有班级');
        if($aClass=='所有班级'){
           $st_map=array(
            'status' => 1
            );  
       }else{
            $st_map=array(
            'status' => 1,
            'class'=>$aClass            
            );  

       }
        
        // dump($classlist);die;
        $page=I('page',1);
        $r=I('r',42);
        $field='';
        $st_order='class asc,code asc';
        $totalCount=$studentModel->where($st_map)->count();
        if($totalCount){
             $data=$studentModel->getListByPage($st_map,$page,$st_order,$r); 
             // dump($data);die;           
        }
        
        $this->assign('data', $data['0']);
        $this->assign('aclass', $aClass);

        $this->assign('classlist', $classlist);

        $this->meta_title = '班级学生信息';
        $this->display('Chengji@Admin/classlist');
    }
            //导入学生名单 上传excel方法
        public function importCourse(){
            
            if(IS_POST){
                $config = array(
                    'maxSize'    =>   30*1024*1024, // 设置附件上传大小
                    'rootPath'   => './Uploads/',
                    'savePath'   =>     'Tmp/',// 设置附件上传目录
                    'saveName'   =>   array('uniqid'),//iconv('utf-8', 'gbk', $save),
                    'exts'       =>    array('xls', 'xlsx'),// 设置附件上传类
                    'autoSub'    =>    true,
                    'subName'    =>    array('date','Y-m'),
                    );
                $upload = new \Think\Upload($config);// 实例化上传类

                // 上传文件
                $info   =   $upload->uploadOne($_FILES['excelData']);      
                $filename = './Uploads/'.$info['savepath'].$info['savename'];
                $exts = $info['ext'];
                // print_r($info);exit;
                if(!$info) {// 上传错误提示错误信息
                      $this->error($upload->getError());
                  }else{
                  // 上传成功
                   $this->read_course($filename, $exts);
                }

            }else{
                $this->assign('meta_title','导入课程信息');
                $this->display('Chengji@Admin/import_course');
            }

        }
        


    /*导入数据方法*/
    protected function read_course($filename, $exts='xls')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        vendor("PHPExcel"); 
        //创建PHPExcel对象，注意，不能少了\ 
        $objPHPExcel = new \PHPExcel();  
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5'); 

        }else if($exts == 'xlsx'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objReader->setReadDataOnly(true);   
        //载入文件
        $objPHPExcel = $objReader->load($filename); 
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$objPHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=4;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell=$currentSheet->getCell($address)->getValue();                
                if($cell instanceof PHPExcel_RichText){//富文本转换字符串
                    $cell  = $cell->__toString();
                }
                $data[$currentRow][$currentColumn]=$cell;
                //print_r($cell);
            } 
        }
        // dump($data);die;
        $this->save_course($data);
    }

    /*保存导入数据*/
    public function save_course($data)
    {
        // dump(date('Y'));
        // dump($data);exit;

 
        $courseModel = $this->couresModel;
        $update_num=0;
        $add_num=0;
        $client_ip=get_client_ip(1);
        foreach ($data as $k=>$v){


             $stdata[$k]=array(
                    'cname'=>$v['B'],
                    'teacher'=>$v['C'],
                    'category'=>$v['D'],
                    'grade'=>$v['E'],                    
                    'number'=>$v['F'],
                    'room'=>$v['G'],
                    'bz'=>$v['H'],
                    'update_ip'=>$client_ip,
                    'year'=>date('Y'),
                    'status'=>1
                    ); 

                $map = array(
                    'cname'=>$v['B'], 
                    'teacher'=> $v['C'],                                
                    'year'=>date('Y'),                  
                    'status'=>1); 
      
                $result = $courseModel->where($map)->find();
                  

                if($result){
                    //更新操作
                    $stdata[$k]['update_time']=NOW_TIME;
                    $up_data = $courseModel->create($stdata[$k]);
                    $result = $courseModel->where($map)->save($up_data);
                    // echo '更新';
                    // dump($up_data);
                    $update_num++;
                    //获取最后一次查询//dump($studentModel->_sql());
                     
                }else{
                    //入库操作                   
                    $adddata=$courseModel->create($stdata[$k]);//要实现自动增加自动验证需调用create函数 
                    // echo '插入';
                    // dump($adddata) ;                  
                    $result = $courseModel->add($adddata);
                    $add_num++;
                  
                }
        
        }
        //die;
        $infotext='本次操作，共导入'.$add_num.'条课程！<br>更新'.$update_num.'条课程信息！';
        // dump($infotext);die;
       $this->success( $infotext, U('Admin/Wckc/importCourse'), 10);

    }





            //导入学生名单 上传excel方法
        public function importstudent(){
            
            if(IS_POST){
                $config = array(
                    'maxSize'    =>   30*1024*1024, // 设置附件上传大小
                    'rootPath'   => './Uploads/',
                    'savePath'   =>     'Tmp/',// 设置附件上传目录
                    'saveName'   =>   array('uniqid'),//iconv('utf-8', 'gbk', $save),
                    'exts'       =>    array('xls', 'xlsx'),// 设置附件上传类
                    'autoSub'    =>    true,
                    'subName'    =>    array('date','Y-m'),
                    );
                $upload = new \Think\Upload($config);// 实例化上传类

                // 上传文件
                $info   =   $upload->uploadOne($_FILES['excelData']);      
                $filename = './Uploads/'.$info['savepath'].$info['savename'];
                $exts = $info['ext'];
                // print_r($info);exit;
                if(!$info) {// 上传错误提示错误信息
                      $this->error($upload->getError());
                  }else{
                  // 上传成功
                   $this->student_import($filename, $exts);
                }

            }else{
                $this->assign('meta_title','导入学生信息');
                $this->display('Chengji@Admin/import_student');
            }

        }
        


    /*导入数据方法*/
    protected function student_import($filename, $exts='xls')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        vendor("PHPExcel"); 
        //创建PHPExcel对象，注意，不能少了\ 
        $objPHPExcel = new \PHPExcel();  
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5'); 

        }else if($exts == 'xlsx'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objReader->setReadDataOnly(true);   
        //载入文件
        $objPHPExcel = $objReader->load($filename); 
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$objPHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=3;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell=$currentSheet->getCell($address)->getValue();                
                if($cell instanceof PHPExcel_RichText){//富文本转换字符串
                    $cell  = $cell->__toString();
                }
                $data[$currentRow][$currentColumn]=$cell;
                //print_r($cell);
            } 
        }
        // dump($data);die;
        $this->save_import($data);
    }

    /*保存导入数据*/
    public function save_import($data)
    {
         // dump($data);exit;

 
        $studentModel = $this->studentModel;
        $update_num=0;
        $add_num=0;
        $client_ip=get_client_ip(1);
        foreach ($data as $k=>$v){


             $stdata[$k]=array(
                    'class'=>$v['A'],
                    'grade'=>$v['B'],
                    'code'=>$v['C'],
                    'name'=>$v['D'],                    
                    'sex'=>$v['E'],
                    'bz'=>$v['F'],
                    'update_ip'=>$client_ip,
                    'status'=>1
                    ); 

                $map = array(
                    'class'=>$v['A'],
                    'grade'=>$v['B'],
                    //'code'=>$v['C'],
                    'name'=>$v['D'],                  
                    'status'=>1); 
                    //dump($map)  ;         
                $result = $studentModel->where($map)->find();
                  

                if($result){
                    //更新操作
                    $stdata[$k]['update_time']=NOW_TIME;
                    $up_data = $studentModel->create($stdata[$k]);
                    $result = $studentModel->where($map)->save($up_data);
                    $update_num++;
                    //获取最后一次查询//dump($studentModel->_sql());
                     
                }else{
                    //入库操作                   
                    $adddata=$studentModel->create($stdata[$k]);//要实现自动增加自动验证需调用create函数                    
                    $result = $studentModel->add($adddata);
                    $add_num++;
                  
                }
         
        }
        $infotext='本次操作，共导入'.$add_num.'条学生数据！<br>更新'.$update_num.'条学生数据！';
        // dump($infotext);die;
       $this->success( $infotext, U('Admin/Wckc/importstudent'), 10);

    }




    public function list_classscore()
    {
            $build = new AdminListBuilder();
            $termlist=D('YearTerm')->field('term_chj as id,term_chj as value')->select();

                

        //标题 到 搜索和筛选 示例
        $build
            ->title('学生成绩列表')
            ->suggest('按学期查询各班成绩')
            ->buttonNew(U('Admin/Student/classscore_bijiao'),'年级成绩对比')
            ->buttonNew(U('Admin/Student/classscore_hz'),'成绩汇总导出excel')
            ->select('学期选择：', 'term', 'select', '', '', '', $termlist);


            $term=I('term',C('CUR_TERM_CHJ'));//学期
            //排序设置
            $order=array(
                'subject'=>'asc',
                'bj_code'=>'asc'

                );
            $classdata=$this->classscoreModel->where(array('term'=>$term))->order($order)->select();
  
        $build->keyId()// text 衍生 默认加载键名为id的值 标题默认为id
                ->keyText('term','学期')
                ->keyText('bj_code','班级编号')->keyText('bj_name','班级') //普通文字 加载对应键名的内容
                ->keyText('subject','学科')->keyText('pinjunfen','平均分')
                ->keyText('youxiulv','优秀率')
                ->keyText('hegelv','合格率')
                ->keyText('hou10renshu','后10%')

                ->keyCreateTime()// time 衍生 默认处理键名 create_time
                ->keyUpdateTime();// time 衍生 默认处理键名 update_time
    
        $build->data($classdata)->display();
       
        }


   /* 导出学生信息*/
    public function export_classscore ()
    {
               for($i=2015;$i<=date(Y);$i++){
                static $k=0;
                $k++;
                $termlist[$k]['value'] = $termlist[$k]['id'] = $i.'上';
                $k++;
                $termlist[$k]['value'] = $termlist[$k]['id'] = $i.'下';
                
                } ;
                $this->assign('termlist',$termlist);
                $aTerm=I('term');
                $this->assign('aTerm',$aTerm);



        //设置排序
        
        $order=array('grade'=>'asc','bj_code'=>'asc');
        $gradelist=$this->gradeModel->field('grade,name')->select();
        $classlist=$this->classModel->where($aMap)->order($order)->select();
        $this->assign('_list', $classlist);
       //dump($aList);
        $this->assign('alist',$aList);
        $this->assign('gradelist',$gradelist);
        $this->meta_title = '导出各科成绩汇总表格';
        $this->display('Student@Admin/export_classscore');
    }
     public function update_grade()
    {
        /*年级升级*/
        $glist=$this->gradeModel->field('grade,year,name')->order('year desc')->select();
      
        foreach ($glist as $key => $value) {
            $map['bj_code']=array('between',$value['year'].'01 ,' .$value['year'].'09');    
            $list=$this->studentModel->where($map)->setField('grade',$value['grade']);
            $info .='共更新'.$value['name'].$list.'名学生信息,成功！\r\n';
        }

        echo '<script language="JavaScript"> alert("';
        echo "$info";
        echo '")';      
       echo '</script>';
       $this->success('更新成功', U('export'),1);

      }
 

    /*班级信息编辑*/
    public function editClass()
    {
        $id=I('id');

    	if(IS_POST){
    		$aclass=$this->classModel->create();
    		//dump($aclass);exit;
    		if ($this->classModel->save($aclass)){
    		    $this->success('编辑成功。');
    		} else {
                $this->error('编辑失败。');
            }
    	}
    	//dump($id);
    	if(!$id){
    		$this->error('班级ID不存在');
    	}else{
    		$data=$this->classModel->find($id);
    		 $builder = new AdminConfigBuilder();
    		  $builder->title('编辑班级信息')->keyId('id','班级ID')->keyText('bj_code','班级编码')
    		  ->keyText('bj_name', '班级名称')->keyText('bj_name2', '班级简称')
    		  ->keyText('headteacher', '班主任')

                //->keyStatus()
                ->keyCreateTime()->keyUpdateTime()
                ->data($data)
                ->buttonSubmit(U('Student/editClass'))->buttonBack()->display();
    	}

    	//dump($data);exit;
    }
    public function studentlist(){
        $bj=$this->classModel->field('bj_code')->find();//获取一条班级记录
        //dump($bj_code);
        
        $map['bj_code']=I('bj_code',$bj['bj_code']);
    	$field="*";
    	$page=I('page');
    	//$data=$this->studentModel->relation(true)->getListByPage($map,$page,$order='st_code asc',$field,$r=20);
    	 //dump($data);die;
    	$builder = new AdminListBuilder();
        //$builder->clearTrash($model);
        //读取微博列表
        $map = array('status' => 1);
        
        $list = $this->studentModel->relation(true)->where($map)->page($page, $r)->select();
        //dump($this->studentModel->relation(true));
        //dump($list);die;
        $totalCount = $this->studentModel->where($map)->count();

        //显示页面

        $builder->title('学生基本信息')
            ->setStatusUrl(U('setStatus'))->buttonRestore()->buttonClear('Student/switch')
            ->keyId()->keyText('st_name', '学生姓名')->keyText('bj_code', '班级编号')->keyText('bj_name', '班级')->keyStatus()->keyCreateTime()
            ->data($list)
            ->pagination($totalCount, $r)
            ->display();
    }


    /* 导出学生信息*/
    public function export ()
    {
        $aGrade=I('grade');
        //dump($aGrade);exit;
        if(!$aGrade){
         unset($aMap['grade']);
         $aMap['status']=1;
        }else{
         $aMap=array(
          'grade'=>$aGrade,
          'status'=>1
            );   
        }
        
        $aList=$this->gradeModel->field('grade,name')->where($aMap)->find();
        //设置排序
        
        $order=array('grade'=>'asc','bj_code'=>'asc');
        $gradelist=$this->gradeModel->field('grade,name')->select();
        $classlist=$this->classModel->where($aMap)->order($order)->select();
        $this->assign('_list', $classlist);
       //dump($aList);
        $this->assign('alist',$aList);
        $this->assign('gradelist',$gradelist);
        $this->meta_title = '导出表格';
        $this->display('Chengji@Admin/export');
    }



}